import itertools
import base64
import json
import random
from set_log import log
import pymysql
from datetime import datetime, timedelta
import time
from no_classfy.file_op import read_txt


def generate_ipark_grade():
    """
    特定：根据正则规则生成指定内容，const pattern1 = /^[GJSYZC]-((1|2|3|4|5)-(1|2)|6|7|8)$/g
    """
    # 定义起始字母和数字组合
    start_letters = ['G', 'J', 'S', 'Y', 'Z', 'C']
    num_part1 = ['1', '2', '3', '4', '5']
    num_part2 = ['1', '2']
    single_nums = ['6', '7', '8']

    # 存储所有可能的结果
    results = [f"{letter}-{num1}-{num2}" for letter, num1,
               num2 in itertools.product(start_letters, num_part1, num_part2)]

    # print("==========One==========",results)
    # 构造第二种情况：单独的6、7或8
    results.extend(f"{letter}-{num}" for letter,
                   num in itertools.product(start_letters, single_nums))
    # print("==========Two==========",results)
    # print(results,'\ntotal:',len(results))

    return results


def picTo64Base(pic):
    """
    图片转换成base64
    pic:"D:/path/to/your/image.jpg"
    """
    # 读取二进制文件
    with open(pic, "rb") as image_file:
        # 使用base64进行编码
        encoded_string = base64.b64encode(image_file.read()).decode()
    return encoded_string


def generate_random_string(charset, length):
    """
    从指定字符集合 charset 中随机生成长度为 length 的字符串。

    :param charset: 字符串形式的字符集合，从中随机抽取字符。
    :param length: 生成的目标字符串长度。
    :return: 随机生成的字符串。
    """
    if not charset or not length:
        return ""

    # 使用 random.choices 从 charset 中随机选择 length 个字符，返回一个列表
    # ''.join 将列表转换成字符串
    random_string = ''.join(random.choices(charset, k=length))
    log.debug(random_string)
    return random_string


def toFacePostBody(code, pic):
    """
    人脸接口数据
    https://gw-uat-jmbos.jomoo.cn/tenant/api/employee/faceUpload
    """
    # content = json.dumps(body,indent=4,ensure_ascii=False)
    # with open('toFacePostBody.txt', 'w') as f:
    #     f.write(content)
    return {"number": code, "faces": picTo64Base(pic)}


def update_payload(payload, **kwargs):
    """
    根据提供的关键字参数更新payload字典。

    :param payload: 原始payload字典
    :param kwargs: 动态参数，应该包含需要更新到payload中的键值对
    :return: 更新后的payload字典
    """
    # 遍历传入的关键字参数
    for key, value in kwargs.items():
        # 检查payload中是否存在该键，存在则更新其值
        if key in payload:
            payload[key] = value
    return payload


def readTxt(file):
    with open(file, 'r', encoding='UTF-8') as f:
        return f.read()


def formatJson(file=None, data=None):
    """
    json串格式化
    """
    if file is not None:
        with open(file=file, mode='r', encoding='utf-8') as f:
            data = f.read()
            content = json.dumps(data, indent=4, ensure_ascii=False)
    elif data is not None:
        content = json.dumps(data, indent=4, ensure_ascii=False)
    log.debug(content)
    return content


def generate_datetimes(start_date, end_date):
    """
    按秒生成指定日期范围内的所有日期时间。

    参数:
        start_date (str): 起始日期时间，格式为 'YYYY-MM-DD HH:MM:SS'
        end_date (str): 结束日期时间，格式为 'YYYY-MM-DD HH:MM:SS'

    返回:
        list: 包含所有按秒生成的日期时间字符串列表
    """
    # 将输入字符串转换为 datetime 对象
    start_datetime = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
    end_datetime = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S')

    # 检查起始日期是否早于结束日期
    if start_datetime > end_datetime:
        raise ValueError("起始日期必须早于或等于结束日期")

    # 初始化结果列表
    datetimes = []

    # 按秒生成日期时间
    current_datetime = start_datetime
    while current_datetime <= end_datetime:
        t = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
        log.debug(t)
        datetimes.append(t)
        current_datetime += timedelta(seconds=1)

    return datetimes


class MySql:
    def __init__(self, host, port, name, psw, db):
        self.conn = pymysql.connect(host=host, port=int(
            port), user=name, password=psw, db=db)

    def execute_sql(self, sql):
        # try:
        # 为了避免连接被服务器关闭,检测进行重连
        self.conn.ping(reconnect=True)
        with self.conn.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchall()
        self.conn.commit()
        # except:
        #     self._conn.rollback()
        return result

    def execute_many(self, query, values):
        """
        :param query: insert into table(field1,field2) values(%s,%s)
        :param values: [(field1_value1,field2_value2),(field1_value3,field2_value4)]
        :return:
        """
        # try:
        # 为了避免连接被服务器关闭,检测进行重连
        self.conn.ping(reconnect=True)
        num = len(values)
        n = 0
        with self.conn.cursor() as cursor:
            while n < num:
                cursor.executemany(query, values[n:n+1000])
                self.conn.commit()
                n += 1000
        # except:
        #     self._conn.rollback()

    def close_all(self):
        self.conn.close()


def _phone():
    """
    生成手机号
    tag：临时
    """
    _ = ''
    for i in range(1, 10000):
        _ += f'1999999{i:0>5}'
        _ += '\n'
    print(_)
    with open('phone.csv', 'w') as f:
        f.write(_)


def _update_sys_user_carId(userFile='usrs.txt', limit=6000):
    """
    更新用户数据
    """
    def _get_emp():
        users = readTxt(userFile)
        emps = []
        for _ in users.split('\n'):
            if _ is not None:
                emps.append(_.split(',')[0])
        log.debug(emps)
        return emps
        # return [for _ in users.split('\n')]
    emps = _get_emp()
    sql_client = MySql(
        '10.1.11.99',
        3306,
        'ipark_test',
        'e09-9476-9d8',
        'ipark_test_sys'
    )
    for idx, emp in enumerate(emps):
        if idx > limit-1:
            break
        if emp is None or emp == '':
            continue
        sql = f"""
        UPDATE sys_user t 
        SET t.card_number = '99999100000000{idx:0>4}' 
        WHERE
        	t.employee_code = '{emp}';    
        """
        log.debug(f'{idx} {sql}')
        sql_client.execute_sql(sql)

    sql_client.close_all()


def _check_emp(userFile='usrs.txt', limit=6000):
    def _get_emp():
        users = readTxt(userFile)
        emps = []
        for _ in users.split('\n'):
            if _ is not None:
                emps.append(_.split(',')[0])
        log.debug(emps)
        return emps
        
    emps = _get_emp()
    sql_client = MySql(
        '10.1.11.99',
        3306,
        'ipark_test',
        'e09-9476-9d8',
        'ipark_test_sys'
    )
    non_emp = {'none': []}
    for idx, emp in enumerate(emps):
        if idx > limit-1:
            break
        if emp is None or emp == '':
            non_emp['none'].append(idx+1)
            continue
        sql = f"""
SELECT
	count(1)
FROM
	sys_user t 
WHERE
	t.employee_code = '{emp}';    
        """
        log.debug(f'{idx} {sql}')
        # sql_client.execute_sql(sql)
        if len(sql_client.execute_sql(sql)) == 0:
            non_emp[emp] = idx+2
    log.info(non_emp)
    sql_client.close_all()


if __name__ == '__main__':
    # rs = generate_random_string("a测_8",30)
    # print(rs)
    # 示例用法
    # charset = "a测_8"
    # length = 50
    # # print(generate_random_string(charset, length)
    # # picTo64Base('./input/girl.png')
    # # toFacePostBody('W00238','./input/girl.png')
    # # generate_random_string()
    # generate_random_string(charset, length)
    # formatJson(r'D:\mytest\input\JSON\3fa1dfdf261bc5862599b1b133d86653-response-msg.txt')
    # sql = 'select * from attend_group'
    # db = MySql(
    #     '10.1.11.99',
    #     3306,
    #     'ipark_test',
    #     'e09-9476-9d8',
    #     'ipark_test_attend'
    # )
    # r = db.execute_sql(sql)
    # print(r)
    # db.close_all()
    # generate_datetimes('2000-07-31 23:59:59','2001-01-01 00:00:01')
    # current = time.strftime("%Y-%m-%d %H:%M:%S")
    # print(current)
    # print(int(current[5:7])<7)
    # end = 1 if int(current[5:7])<7 else 2
    # print(end)
    # print(current[0:4])
    # _phone()
    _update_sys_user_carId(limit=6001,userFile='usrs.txt')
    # _check_emp(limit=6001)
